/*
 * 项目名称:common_utils 类名称:RequestUtil 包名称:com.joyintech.util 修改履历: 日期 修正者 主要内容 2016年07月12日 system
 * 初版做成 Copyright (c) 2016-2017 兆尹科技
 */
package com.sinbader.xiaole.common.utils;

import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletRequest;
import java.net.URLDecoder;
import java.net.URLEncoder;
import java.util.Enumeration;
import java.util.HashMap;
import java.util.Map;
import java.util.logging.Logger;

/**
 * HTTP请求处理工具类
 *
 * @author system
 * @version 1.0
 */
public class RequestUtil {
    
    /**
     * 特殊字符
     */
    private static final String[] SP_STR = new String[]{"!","@","#","$", "%", "^", "&" ,"*", "+"};

    /**
     * Logger
     */
    private static final Logger LOGGER = Logger.getLogger(RequestUtil.class.getName());

    /**
     * 排序方式名称 asc:正序 | desc:倒序
     */
    public static final String SORT_ORDER = "sortOrder";

    /**
     * 将request查询参数封装至Map
     *
     * @param request 请求
     * @param printLog 是否打印日志
     * @return 参数Map
     */
    public static Map<String, Object> getParameters(HttpServletRequest request, boolean printLog) {
        Enumeration<String> enume = request.getParameterNames();
        Map<String, Object> map = new HashMap<String, Object>();
        while (enume.hasMoreElements()) {
            String key = enume.nextElement();
            String value = request.getParameter(key);
            try {
                boolean flag = false;
                for(String c : SP_STR) {
                    if(value.contains(c)) {
                        flag = true;
                        break;
                    }
                }
                if(flag) {
                    // 如果有特殊字符，则进行URL编码
                    value = URLEncoder.encode(value, "utf-8");
                }
                value = URLDecoder.decode(value, "utf-8");
            }
            catch (Exception e) {
            }
            value = StringUtils.delHTMLTag(value);
//            value = StringsUtil.StringFilter(value);
            map.put(key, value);
            if (printLog) {
                LOGGER.info(key + "==>" + value);
            }
        }
        if (map.get(SORT_ORDER) != null) {
            map.put(SORT_ORDER, "asc");
        }
        return map;
    }

    /**
     * 将request查询参数封装至Map
     *
     * @param request 请求
     * @return 参数Map
     */
    public static Map<String, Object> getParameters(HttpServletRequest request) {

        return getParameters(request, false);
    }

    /**
     * 获取请求方IP
     *
     * @return 客户端Ip
     */
    public static String getClientIp() {
        HttpServletRequest request = getCurrentRequest();
        String xff = request.getHeader("x-forwarded-for");
        if (xff == null) {
            xff = request.getRemoteAddr();
        }
        if ("0:0:0:0:0:0:0:1".equals(xff)) {
            xff = "127.0.0.1";
        }
        return xff;
    }

    /**
     * 主要功能:获取请求方IP 注意事项:无
     *
     * @param request HttpServletRequest对象
     * @return IP地址
     */
    public static String getIpAddrByRequest(HttpServletRequest request) {
        String ip = request.getHeader("x-forwarded-for");
        if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
            ip = request.getHeader("Proxy-Client-IP");
        }
        if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
            ip = request.getHeader("WL-Proxy-Client-IP");
        }
        if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
            ip = request.getRemoteAddr();
        }

        if ("0:0:0:0:0:0:0:1".equals(ip)) {
            ip = "127.0.0.1";
        }
        return ip;
    }

    /**
     * 获取完整的请求URL
     *
     * @param request 请求
     * @return URL
     */
    public static String getRequestUrl(HttpServletRequest request) {
        return request.getRequestURL().toString();
    }

    /**
     * 获得请求路径（去除URL中的参数）
     *
     * @param request 请求
     * @return 请求路径
     */
    public static String getRequestPath() {
        HttpServletRequest request = getCurrentRequest();
        String requestPath = request.getRequestURI() + "?" + request.getQueryString();
        if (requestPath.indexOf("&") > -1) {
            // 去掉其他参数
            requestPath = requestPath.substring(0, requestPath.indexOf("&"));
        }
        // 去掉项目路径
        requestPath = requestPath.substring(request.getContextPath().length() + 1);
        return requestPath;
    }

    /**
     * 主要功能:获取request 注意事项:无
     *
     * @return HttpServletRequest
     */
    public static HttpServletRequest getCurrentRequest() {
        return ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getRequest();
    }
}
